package awesome.request.handler;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

import awesome.ServerConfig;
import awesome.request.Request;
import awesome.request.RequestQueue;

/**
 * Receives incoming requests, serializes, and pushes to the RequestQueue.
 * 
 * @author Chris Carpenter
 * 
 */
public class RequestHandler implements Runnable {
	
	private RequestQueue requestQueue;
	
	private ServerSocket serversocket;
	
	public RequestHandler(RequestQueue _requestQueue) {
		this.requestQueue = _requestQueue;
	}
	
	@Override
	public void run() {
		
		try {
			serversocket = new ServerSocket(
					Integer.parseInt(ServerConfig.INSTANCE.getProperty("server.port")));
			serversocket.setSoTimeout(5000); //allows check for thread interruption
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Socket newConnection;
		Request newRequest;
		while (!Thread.currentThread().isInterrupted()) {
			try {
				newConnection = serversocket.accept();
				newRequest = new Request(newConnection); //serialize
				requestQueue.add(newRequest);
			} catch (SocketTimeoutException e) {
				//expected, do nothing
			}catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
